/*
 * @lc app=leetcode.cn id=116 lang=java
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */ 

// @lc code=start
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        // 单个节点的递归没办法解决问题，比如连接5和6靠单个节点递归是实现不了的，所以考虑加节点递归
        connectTwoNodes(root.left, root.right);
        return root;
    }

    /**
     * 明确函数定义为连接左右节点，并且搞定非父相邻节点
     * 
     * @param n1
     * @param n2
     */
    public void connectTwoNodes(Node n1, Node n2) {
        if (n1 == null || n2 == null) {
            return;
        }

        // 连接2 3
        n1.next = n2;
        
        // 连接4 5
        connectTwoNodes(n1.left, n1.right);
        // 连接6 7
        connectTwoNodes(n2.left, n2.right);
        // 连接5 6
        connectTwoNodes(n1.right, n2.left);
    }
}
// @lc code=end

